<?php

include_once './config.php';
include_once './User.php';
include_once './I18N.php';
include_once './Situare.php';
include_once './Utils.php';
include_once './log4php/Logger.php';

Logger::configure('./log4j.properties');

Display::$log = Logger::getLogger(basename(__FILE__));

class Display {

    public static $log;
//
//    public function __construct() {
//        $this->log = Logger::getLogger(__FILE__);
//    }

    /**
     * Appends the resources dir path prefix to the resource name, e.g.
     * self::getResource('images/icon/settings_icon.png') returns './resources/images/icon/settings_icon.png'
     *
     * @param object $resourceName
     * @return
     */
    public static function getResource($resourceName) {
        return RESOURCES_DIR_PATH . $resourceName;
    }

    /**
     * Renders HTML page from the parameters.
     * 
     * @param object $title [optional] page title
     * @param object $header [optional] rendered HTML header content (e.g. scripts, stylesheets)
     * @param object $body [optional] rendered HTML body content
     * @param Situare $situare [mandatory]
     * @return 
     */
    public static function renderHTMLPage($situare, $title='', $header=null, $body=null) {
        self::$log->debug("[START] " . __METHOD__);

        /**
         * @var User
         */
        $user = $situare->getUser();

        $html = '<?xml version="1.0" encoding="UTF-8"?>';
// $html .= "\n" . '<!DOCTYPE html PUBLIC "-//WAPFORUM//DTD XHTML Mobile 1.0//EN" "http://www.wapforum.org/DTD/xhtml-mobile10.dtd">';
        $html .= "\n" . '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">';
        $html .= "\n" . '<html xmlns="http://www.w3.org/1999/xhtml">';
// HTML head
        $html .= "\n" . '<head>';
        $html .= "\n" . '<title>' . $title . '</title>';
        if (isset($header)) {
            $html .= $header;
        }

        $html .= "\n" . '</head>';
// HTML body
//
//


        $html .= "\n" . '<body onresize="if(window.crosshairControl!=undefined) window.crosshairControl.draw();" onload="if(getLocation) getLocation()" >';

        $html .= "\n" . self::renderOSMScript($situare, isset($user->fb_location) ? $user->fb_location->lon : 0, isset($user->fb_location) ? $user->fb_location->lat : 0, isset($user->fb_location) ? self::getMapZoomLevel($user->fb_location) : 1, $user);

        if (isset($body)) {
            $html .= $body;
        }


        $html .= "\n" . "
	
	<script type='text/javascript'>
		  var _gaq = _gaq || [];
		  _gaq.push(['_setAccount', 'UA-12562196-2']);
		  _gaq.push(['_trackPageview']);

		  (function() {
			    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
			    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
			    (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(ga);
		  })();

</script>";


        $html .= "\n" . '</body>';
        $html .= "\n" . '</html>';

        self::$log->debug("[ END ] " . __METHOD__);
        return $html;
    }

    /**
     * Returns the content of the specified file.
     *
     * @param string $path
     */
    private static function readFileContent($path) {
        $return = file_get_contents($path);

        if (!$return) {
            self::$log->error("Can't read file '" . $path . "'");
            return NULL;
        }

        return $return;
    }

    /**
     * Renders the HTML header of the main.php page.
     *
     * @return
     */
    public static function renderMainHeader($situare) {
        self::$log->debug("[START] " . __METHOD__);

        $html = "\n" . '<link href="resources/styles/list_view.css" rel="stylesheet" type="text/css" />';
        $html .= "\n" . '<link href="resources/styles/message_window.css" rel="stylesheet" type="text/css" />';
        $html .= "\n" . '<link href="resources/styles/details_window.css" rel="stylesheet" type="text/css" />';
//google javascript maps
        $html .= "\n" . '<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"></script>';
// dynamic loader script
        $html .= "\n" . '<script type="text/javascript" src="http://' . $_SERVER['SERVER_NAME'] . '/dynamicLoader.js"></script>';
// popup
        $html .= "\n" . '<script type="text/javascript" src="http://' . $_SERVER['SERVER_NAME'] . '/popup.js"></script>';

//locator
        $html .= "\n" . '<script type="text/javascript" src="http://' . $_SERVER['SERVER_NAME'] . '/location.js"></script>';

        self::$log->debug("[ END ] " . __METHOD__);
        return $html;
    }

    /**
     * Renders the main.php body content.
     *
     * @param Situare $situare
     * @return unknown_type
     */
    public static function renderMainBody($situare) {
        self::$log->debug("[START] " . __METHOD__);

        $user = $situare->getUser();

        $html = "\n" . '<div id="wrapper">';
        $html .= self::renderMyInfo($situare, $user);
        $html .= "\n" . '<div class="separator"></div>';
        $html .= self::renderTabView($situare, $user);
        $html .= "\n" . '</div>';  // wrapper
        $html .= self::render_footer();

        if (isset($user->fb_location)) {
            $html .= self::renderLocationUpdateForm($user->fb_location->lon, $user->fb_location->lat);
        } else {
            $html .= self::renderLocationUpdateForm("0", "0");
        }

        self::$log->debug("[ END ] " . __METHOD__);
        return $html;
    }

    /**
     * Renders onclick function for cancel button
     * 
     * @param Situare $situare
     *
     * @return
     */
    public static function renderCancelButtonOnClick($situare) {
        self::$log->debug("[START] " . __METHOD__);

        if (!($situare->inCanvas())) {
            $html = ' onClick="window.location = \'' . $situare->getLogoutURL() . '\';" ';
        } else {
            $html = '';
        }

        self::$log->debug("[ END ] " . __METHOD__);
        return $html;
    }

    /**
     * Renders the application title bar.
     * 
     * @param Situare $situare 
     * 
     * @return 
     */
    public static function renderTitleBar($situare) {
        self::$log->debug("[START] " . __METHOD__);

        $html = '<div id="titleBar">' . "\n";

        $html .= '<div id="leftBar">' . "\n";
        $html .= '<img src="' . self::getResource('images/icon/situare_icon_new.png') . '" />' . "\n";
        $html .= '<span style="color: white; font-family: verdana; position: relative; top: -4px; font-size: 12px;"> Beta </span>' . "\n";
        $html .= '</div>' . "\n";   //leftBar

        $html .= '<div id="rightBar">' . "\n";

        $html .= '<div id="statusBar">' . "\n";
        $html .= '<div id="gpsStatus">' . "\n";
        $html .= '<img src="' . self::getResource('images/icon/info/status_gps_icon_N.png') . '" />' . "\n";
        $html .= '</div>' . "\n";   //gpsStatus
        $html .= '<div id="reloadStatus">' . "\n";
        $html .= '<img src="' . self::getResource('images/icon/info/status_reload_icon_A.png') . '" />' . "\n";
        $html .= '</div>' . "\n";   //reloadStatus
        $html .= '</div>' . "\n";   //statusBar

        $html .= '<div id="verticalSep" style="margin-right:75px;">' . "\n";
        $html .= '<img src="' . self::getResource('images/background/top_separtor.png') . '" />' . "\n";
        $html .= '</div>' . "\n";   //verticalSep

        $html .= '<div id="settingsBar">' . "\n";
        $html .= '<table id="tableButtons" cellpadding="0" cellspacing="0">' . "\n";
        $html .= '<tr>' . "\n";
        $html .= '<td id="settings_td" style="visibility:hidden;"><img id="settings_button" src="' . self::getResource('images/icon/settings_icon.png') . '" title="' . I18n::getMessage('tooltips.settingsicon') . '" /></td>' . "\n";
        $html .= '<td><img id="help_button" onclick=\'window.open("http://www.situare.net/images/help/help.png","Help")\' src="' . self::getResource('images/icon/help_icon.png') . '" title="' . I18n::getMessage('tooltips.helpicon') . '" style="border: 0pt none ;"/></td>' . "\n";
        $html .= '<td><img id="cancel_button"' . self::renderCancelButtonOnClick($situare) . 'src="' . self::getResource('images/icon/cancel_icon.png') . '" title="' . I18n::getMessage('tooltips.exiticon') . '"/></td>' . "\n";
        $html .= '</tr>' . "\n";
        $html .= '</table>' . "\n";
        $html .= '</div>' . "\n";   //settingsBar

        $html .= '</div>' . "\n";   //rightBar

        $html .= '</div>' . "\n";   //titleBar

        self::$log->debug("[ END ] " . __METHOD__);
        return $html;
    }

    /**
     * Renders the My Info section.
     *
     * @param User $user
     * @return
     */
    public static function renderMyInfo($situare, $user) {
        self::$log->debug("[START] " . __METHOD__);

        $html = '<div id="myInfo">';

        $html .= '<div id="myInfoBlock">';

        $html .= '<div class="photoArea">';
        $html .= '<img src="' . self::getUserProfileUrl($user) . '" />';
        $html .= '</div>';      // photoArea

        $html .= '<div class="texArea">';
        $html .= '<table class="tableIDinfo" cellspacing="0" cellpadding="0">';
        $html .= '<tr>';
        $html .= '<td colspan="2" class="IDname">' . $user->fb_name . '</td>';
        $html .= '</tr>';
        $html .= '<tr>';
        $html .= '<td colspan="2" class="separatorID"></td>';
        $html .= '</tr>';
        $html .= '<tr>';
        $html .= '<td class="iconID"><img src="' . self::getResource('images/icon/list_small.png') . '"/></td>';
        $html .= '<td class="infoID">' . (isset($user->fb_location) ? $user->fb_location->data : '') . '</td>';
        $html .= '</tr>';
        $html .= ' <tr>';
        $html .= '<td class="iconID"><img src="' . self::getResource('images/icon/compas_small.png') . '"/></td>';
        $html .= '<td class="infoID">' . (isset($user->fb_location) ? $user->fb_location->address : I18n::getMessage('location.unknown')) . '</td>';
        $html .= '</tr>';
        $html .= '<tr>';
        $html .= '<td class="iconID"><img src="' . self::getResource('images/icon/clock_small.png') . '"/></td>';
        $html .= '<td class="infoID">' . (isset($user->fb_location) ? self::epochToAgo($user->fb_location->timestamp) : I18n::getMessage('time.unknown')) . '</td>';
        $html .= '</tr>';
        $html .= '<tr>';
        $html .= '<td colspan="2" class="emptyID"></td>';
        $html .= '</tr>';
        $html .= '</table>';
        $html .= '</div>';      // texArea

        $html .= '<div class="moreInfoArea verticalLine">';
        $html .= '<div id="relInfo" style="opacity:0.4;filter:alpha(opacity=40)" onmouseover="this.style.opacity=1;if(this.filters){this.filters.alpha.opacity=100}" onmouseout="this.style.opacity=0.4;if(this.filters){this.filters.alpha.opacity=40}">';
        $html .= '<img src="' . self::getResource('images/icon/reload_icon.png') . '" title="' . I18n::getMessage('tooltips.refreshicon') . '" onclick="window.location.href=\'' . HOME_URL . '\';" />';
        $html .= '</div>';
        $html .= '<div id="sendInfo" style="opacity:0.4;filter:alpha(opacity=40)" onmouseover="this.style.opacity=1;if(this.filters){this.filters.alpha.opacity=100}" onmouseout="this.style.opacity=0.4;if(this.filters){this.filters.alpha.opacity=40}">';
        $html .= '<img src="' . self::getResource('images/icon/sendPosition_icon.png') . '" title="' . I18n::getMessage('tooltips.sendicon') . '" onclick="revealModal(\'modalPage\')" />';
        $html .= '</div>';
        $html .= '</div>';      // moreInfoArea

        $html .= '</div>';      // myInfoBlock

        $html .= '</div>';      // myInfo

        self::$log->debug("[ END ] " . __METHOD__);
        return $html;
    }

    /**
     * Renders the List View section containing the given list of friends.
     * 
     * @param object $friends_array array of friends
     * @return 
     */
    public static function renderListView($situare, $friends_array, $user) {
        self::$log->debug("[START] " . __METHOD__);

        $html = "\n" . '<div id="listInfoView">';

        foreach ($friends_array as $friendId => $friend) {
            $html .= self::renderListInfoBlock($situare, $friend, $user);
        }

        $html .= "\n" . '</div>';

        self::$log->debug("[ END ] " . __METHOD__);
        return $html;
    }

    /**
     * Renders the Info Block of a friend.
     * 
     * @param User $friend
     * @return 
     */
    public static function renderListInfoBlock($situare, $friend, $user) {
        self::$log->debug("[START] " . __METHOD__);

        if (!isset($friend)) {
            return '';
        }

        $html = "\n" . '<div class="infoBlock">';

        $html .= "\n" . '<div class="photoArea">';
        $html .= "\n" . '<img src="' . self::getUserProfileUrl($friend) . '" />';
        $html .= "\n" . '</div>';      // photoArea

        $html .= "\n" . '<div class="texArea">';
        $html .= "\n" . '<table class="tableIDinfo" cellspacing="0" cellpadding="0">';
        $html .= "\n" . '<tr>';
        $html .= "\n" . '<td colspan="2" class="IDname">' . $friend->fb_name . '</td>';
        $html .= "\n" . '</tr>';
        $html .= "\n" . '<tr>';
        $html .= "\n" . '<td colspan="2" class="separatorID"></td>';
        $html .= "\n" . '</tr>';
        $html .= "\n" . '<tr>';
        $html .= "\n" . '<td class="iconID"><img src="' . self::getResource('images/icon/list_small.png') . '"/></td>';
        $html .= "\n" . '<td class="infoID">' . (isset($friend->fb_location) ? $friend->fb_location->data : '') . '</td>';
        $html .= "\n" . '</tr>';
        $html .= "\n" . '<tr>';
        $html .= "\n" . '<td class="iconID"><img src="' . self::getResource('images/icon/compas_small.png') . '"/></td>';
        $html .= "\n" . '<td class="infoID">' . (isset($friend->fb_location) ? $friend->fb_location->address : I18n::getMessage('location.unknown')) . '</td>';
        $html .= "\n" . '</tr>';
        $html .= "\n" . '<tr>';
        $html .= "\n" . '<td class="iconID"><img src="' . self::getResource('images/icon/clock_small.png') . '"/></td>';
        $html .= "\n" . '<td class="infoID">' . (isset($friend->fb_location) ? self::epochToAgo($friend->fb_location->timestamp) : I18n::getMessage('time.unknown')) . '</td>';
        $html .= "\n" . '</tr>';
        $html .= "\n" . '<tr>';
        $html .= "\n" . '<td colspan="2" class="emptyID"></td>';
        $html .= "\n" . '</tr>';
        $html .= "\n" . '</table>';
        $html .= "\n" . '</div>';      // texArea

        $html .= "\n" . '<div class="moreInfoArea">';
        $html .= "\n" . '<div class="distanceInfo">' . self::renderDistanceIcon($friend, $user) . self::renderDistance($friend, $user) . '</div>';

        $dist = self::computeDistance($user, $friend);
        $ulon = $dist > -1 ? $user->fb_location->lon : 0;
        $ulat = $dist > -1 ? $user->fb_location->lat : 0;
        $fid = $dist > -1 ? $friend->fb_uid : 0;

        $html .= "\n" . '<div class="mapInfo"' . ($dist > -1 ? ('onclick="activateTab(\'mapView\'); dynamicOSMLoad(' . ($fid != 0 ? ('function(){if(getLocation) getLocation(); layerFriends.showMeAndMyFriend(null, null, ' . $fid . ');}') : '') . ');"') : '') . '>';
        $html .= '<div id="mapInfoImg"' . ($dist > -1 ? ('style="opacity:0.6;filter:alpha(opacity=60)" onmouseover="this.style.opacity=1;if(this.filters){this.filters.alpha.opacity=100}" onmouseout="this.style.opacity=0.6;if(this.filters){this.filters.alpha.opacity=60}"') : 'style="opacity:0.2;filter:alpha(opacity=20)"') . ' >';
        $html .= "\n" . '<img src="' . self::getResource('images/icon/info_icon.png') . '" title="' . I18n::getMessage('tooltips.infoicon') . '" />';
        $html .= "\n" . '</div>';      // mapInfoImg
        $html .= "\n" . '</div>';      // mapInfo
        $html .= "\n" . '</div>';      // moreInfoArea

        $html .= "\n" . '</div>';      // infoBlock

        self::$log->debug("[ END ] " . __METHOD__);
        return $html;
    }

    /**
     * Renders the Tab View component.
     * 
     * @param object $user
     * @return 
     */
    public static function renderTabView($situare, $user) {
        self::$log->debug("[START] " . __METHOD__);

// javascript function for switching the tab content
        $html = "\n" . '<script type="text/javascript">';
        $html .= "\n" . 'function activateTab(tab){';
        $html .= "\n" . 'var tabs = new Array();';
        $html .= "\n" . 'tabs["lwMenuBlock"] = "listView";';
        $html .= "\n" . 'tabs["mwMenuBlock"] = "mapView";';
        $html .= "\n" . 'for (var tabDiv in tabs) {';
        $html .= "\n" . 'if (tab == tabs[tabDiv]) {';
        $html .= "\n" . 'document.getElementById(tabs[tabDiv]).style.display = "block";';
        $html .= "\n" . 'document.getElementById(tabDiv).style.background="url(' . self::getResource('images/button/view_buttonSelect.png') . ') -17px 4px no-repeat";';
        $html .= "\n" . '}';
        $html .= "\n" . 'else {';
        $html .= "\n" . 'document.getElementById(tabs[tabDiv]).style.display = "none";';
        $html .= "\n" . 'document.getElementById(tabDiv).style.background="";';
        $html .= "\n" . '}';
        $html .= "\n" . '}';
        $html .= "\n" . '}';
        $html .= "\n" . '</script>';

        $html .= "\n" . '<div id="scrollArea">';
        $html .= "\n" . '<div id="menuListView">';
        $html .= "\n" . '<div id="leftMenuBlock">';
        $html .= "\n" . '</div>';  // leftMenuBlock
        $html .= "\n" . '<div id="centerMenuBlock">';
        $html .= "\n" . '<div id="lwMenuBlock" onclick="activateTab(\'listView\')">';
        $html .= "\n" . '<img src="' . self::getResource('images/icon/listView_icon.png') . '" />';
        $html .= "\n" . '<h1>' . I18n::getMessage('tabview.listview') . '</h1>';
        $html .= "\n" . '</div>';  // lwMenuBlock
        $html .= "\n" . '<div id="centerSeparator">';
        $html .= "\n" . '</div>';  // centerSeparator
        $html .= "\n" . '<div id="mwMenuBlock" onclick="activateTab(\'mapView\');dynamicOSMLoad(function(){if(crosshairControl!=undefined) crosshairControl.draw(); if(getLocation) getLocation();});">';
        $html .= "\n" . '<img src="' . self::getResource('images/icon/earthView_icon.png') . '" />';
        $html .= "\n" . '<h1>' . I18n::getMessage('tabview.mapview') . '</h1>';
        $html .= "\n" . '</div>';  // mwMenuBlock
        $html .= "\n" . '</div>';  // centerMenuBlock
        $html .= "\n" . '<div id="rightMenuBlock">';
        $html .= "\n" . '</div>';  // rightMenuBlock
        $html .= "\n" . '</div>';  // menuListView

        $html .= "\n" . '<div id="contentBlock">';
        $html .= "\n" . '<div id="listView" style="display: none;">';
        $html .= self::renderListView($situare, $user->getFriends(), $user);
        $html .= "\n" . '</div>';  // listView
        $html .= "\n" . '<div id="mapView" style="display: none; margin-left: 7px;">';
        $html .= self::renderOSM($situare, isset($user->fb_location) ? $user->fb_location->lon : 0, isset($user->fb_location) ? $user->fb_location->lat : 0, isset($user->fb_location) ? self::getMapZoomLevel($user->fb_location) : 10, $user);
        $html .= "\n" . '</div>';  // mapView
        $html .= "\n" . '</div>';  // contentBlock
        $html .= "\n" . '</div>';  // scrollArea
        $html .= "\n" . '<script type="text/javascript">';
        $html .= "\n" . 'activateTab("listView");';
        $html .= "\n" . '</script>';

        self::$log->debug("[ END ] " . __METHOD__);
        return $html;
    }

    public static function renderOSMScript($situare, $center_lon=null, $center_lat=null, $zoom='1', $user=null) {
        self::$log->debug("[START] " . __METHOD__);

        $center_lon = ($center_lon != null) ? $center_lon : 'null';
        $center_lat = ($center_lat != null) ? $center_lat : 'null';

        $html = "\n" . '<script type="text/javascript">';
        $html .= "\n" . 'var layerFriends;';
        $html .= "\n" . 'function loadOSM() {';
        $html .= "\n" . 'layerFriends = initOSM(' . $center_lon . ', ' . $center_lat . ', ' . $zoom . ', "map");';

        if ($user) {
            foreach ($user->getFriends(false) as $key => $value) {
                $html .= self::renderOSMUserLocation($situare, $value, $user);
            }
        } else {
            self::$log->error('Can\'t get the logged in user!');
        }
        $html .= "\n" . 'layerFriends.setOverlay();';

        $html .= "\n" . '}';

        $html .= "\n" . 'function dynamicOSMLoad(postFunc){';
        $html .= "\n" . 'var fileUrls = new Array();';
        $html .= "\n" . 'fileUrls[0] = \'http://' . $_SERVER['SERVER_NAME'] . '/gmaps.js\';';
        $html .= "\n" . 'var checkers = new Array();';
        $html .= "\n" . 'checkers[0] = function(){return window.initOSM!=undefined};';
        $html .= "\n" . 'loadScripts(fileUrls, checkers, loadOSM, 0, postFunc);';
        $html .= "\n" . '}';
        $html .= "\n" . '</script>';

        self::$log->debug("[ END ] " . __METHOD__);
        return $html;
    }

    /**
     * Renders the map <div> HTML element and the JavaScript element, making OSM from the <div>.
     * 
     * @param object $center_lon [optional] The longitude part of the map center location. 
     * @param object $center_lat [optional] The latitude part of the map center location.
     * @param object $zoom [optional] The map zoom level.
     * @return HTML text
     */
    public static function renderOSM($situare, $center_lon=null, $center_lat=0, $zoom='10') {
        self::$log->debug("[START] " . __METHOD__);

        $center_lon = ($center_lon != null) ? $center_lon : 'null';
        $center_lat = ($center_lat != null) ? $center_lat : 'null';

        $html = "\n" . '<div id="map" style="width:100%; height:440px;"><div id="mapInitText">' . I18n::getMessage('map.waitforinit') . '</div></div>';

        self::$log->debug("[ END ] " . __METHOD__);
        return $html;
    }

    public static function renderOSMUserLocation($situare, $friend, $user) {
        self::$log->debug("[START] " . __METHOD__);

        if ($friend->fb_location == null || $friend->fb_location->lon == null || $friend->fb_location->lat == null) {
            return '';
        }

        static $lastIndex = 0;

        ++$lastIndex;

        $html = "\n" . 'var data' . $lastIndex . ' = new Object();';
        $html .= "\n" . 'data' . $lastIndex . '.uid = ' . $friend->fb_uid . ';';
        $html .= "\n" . 'data' . $lastIndex . '.longitude = ' . $friend->fb_location->lon . ';';
        $html .= "\n" . 'data' . $lastIndex . '.latitude = ' . $friend->fb_location->lat . ';';
        $html .= "\n" . 'data' . $lastIndex . '.imgurl = "' . self::getUserProfileUrl($friend) . '";';
        $html .= "\n" . 'data' . $lastIndex . '.popupContentHTML = \'' . str_replace("\n", "", self::renderMapPopup($situare, $friend, $user)) . '\';';
        $html .= "\n" . 'layerFriends.createFriendMarker(data' . $lastIndex . ');';

        self::$log->debug("[ END ] " . __METHOD__);
        return $html;
    }

    /**
     * Renders the content of the given friend's popup balloon.
     *
     * @param $friend uid of the given friend
     * @return unknown_type HTML code sequence
     */
    public static function renderMapPopup($situare, $friend, $user) {
        self::$log->debug("[START] " . __METHOD__);

        $html = '';

        $html .= "\n" . '<div id="popup_wrapper">';

        $html .= "\n" . '<div id="popup_headerBar">';
        $html .= "\n" . '<div id="popup_leftBar">';
        $html .= "\n" . '<div id="popup_leftHeader">';
        $html .= "\n" . '<img src="' . self::getResource('images/pop_up/iconDetail.png') . '" />';
        $html .= "\n" . '</div>';   // leftHeader
        $html .= "\n" . '<div id="popup_rightHeader"><h1>Details info.</h1>';
        $html .= "\n" . '</div>';   // rightHeader
        $html .= "\n" . '</div>';   // leftBar
        $html .= "\n" . '<div id="popup_rightBar">';
        $html .= "\n" . '<div id="popup_leftNav">';
        $html .= "\n" . '<img src="' . self::getResource('images/pop_up/bw_button.png') . '" onclick="layerFriends.selectNextPopup(false);"/>';
        $html .= "\n" . '</div>';   // leftNav
        $html .= "\n" . '<div id="popup_rightNav">';
        $html .= "\n" . '<img src="' . self::getResource('images/pop_up/fw_button.png') . '" onclick="layerFriends.selectNextPopup(true);"/>';
        $html .= "\n" . '</div>';   // rightNav
        $html .= "\n" . '</div>';   // rightBar
        $html .= "\n" . '</div>';   // headerBar

        $html .= "\n" . '<div id="popup_mainArea">';
        $html .= "\n" . '<div id="popup_horizLine"></div>';
        $html .= "\n" . '<div id="popup_mainDetail">';
        $html .= "\n" . '<div id="popup_photoDetail">';
        $html .= "\n" . '<img src="' . self::getUserProfileUrl($friend) . '" />';
        $html .= "\n" . '</div>';   // photoDetail

        $html .= "\n" . '<div id="popup_personalDetail">';
        $html .= "\n" . '<div id="popup_nameDetail">' . $friend->fb_name . '</div>';
        $html .= "\n" . '<div id="popup_separatorD"></div>';
        $html .= "\n" . '<div id="popup_distanceDetail">';
        $html .= "\n" . self::renderDistanceIcon($friend, $user) . self::renderDistance($friend, $user);
        $html .= "\n" . '</div>';   // distanceDetail
        $html .= "\n" . '</div>';   // personalDetail
        $html .= "\n" . '</div>';   // mainDetail

        $html .= "\n" . '<div id="popup_moreDetail">';
        $html .= "\n" . '<div id="popup_topListArea">';
        $html .= "\n" . '</div>';   // topListArea
        $html .= "\n" . '<div id="popup_mainPossitionInfo">';
        $html .= "\n" . '<table class="popup_tableInfo" cellspacing="0" cellpadding="0">';
        $html .= "\n" . '<tr>';
        $html .= "\n" . '<td class="popup_iconID"><img src="' . self::getResource('images/icon/list_small.png') . '"/></td>';
        $html .= "\n" . '<td class="popup_infoID"><p>' . $friend->fb_location->data . '</p></td>';
        $html .= "\n" . '</tr>';
        $html .= "\n" . '<tr>';
        $html .= "\n" . '<td colspan="2" class="popup_map popup_separatorID"></td>';
        $html .= "\n" . '</tr>';
        $html .= "\n" . '<tr>';
        $html .= "\n" . '<td class="popup_iconID"><img src="' . self::getResource('images/icon/compas_small.png') . '"/></td>';
        $html .= "\n" . '<td class="popup_infoID"><p>' . (isset($friend->fb_location) ? $friend->fb_location->address : '') . '</p></td>';
        $html .= "\n" . '</tr>';
        $html .= "\n" . '<tr>';
        $html .= "\n" . '<td colspan="2" class="popup_map popup_separatorID"></td>';
        $html .= "\n" . '</tr>';
        $html .= "\n" . '<tr>';
        $html .= "\n" . '<td class="popup_iconID"><img src="' . self::getResource('images/icon/clock_small.png') . '"/></td>';
        $html .= "\n" . '<td class="popup_infoID"><p>' . (isset($friend->fb_location) ? self::epochToAgo($friend->fb_location->timestamp) : '') . '</p></td>';
        $html .= "\n" . '</tr>';
        $html .= "\n" . '</table>';
        $html .= "\n" . '</div>';   // mainPossitionInfo

        $html .= "\n" . '<div class="popup_endListArea">';
        $html .= "\n" . '</div>';   // endListArea
        $html .= "\n" . '</div>';   // moreDetail
        $html .= "\n" . '</div>';   // mainArea

        $html .= "\n" . '<div id="popup_footerArea">';
        $html .= "\n" . '</div>';   // footerArea
        $html .= "\n" . '</div>';   // wrapper

        self::$log->debug("[ END ] " . __METHOD__);

        return str_replace("'", "&#039;", $html);
    }

    /**
     * Returns the URL address to the given user's profile photo or url to the default profile picture.
     *
     * @param object $user [mandatory] if null, then the currently logged in user is considered
     * @return url address
     */
    public static function getUserProfileUrl($user) {
        return (($user && $user->fb_pic_url) ? $user->fb_pic_url : DEFAULT_PROFILE_PHOTO_URL);
    }

    /**
     * Returns the map zoom level according to the user's location:
     * - if not specified, then zoom level to see the whole world
     * - if specified, then the default level
     * 
     * @param object $location [optional]
     * @return 
     */
    public static function getMapZoomLevel($location=null) {
        if ($location == null || $location->lon == null || $location->lon == '' || $location->lat == null || $location->lat == '') {
            return 1;   // with level 0 the world is too small :)
        } else {
            return MAP_DEFAULT_ZOOM_LEVEL;
        }
    }

    /**
     * Renders the location update form.
     *
     * @param string $lon longitude part of the new location coordinate
     * @param string $lat latitude part of the new location coordinate
     * @param string $actionurl [optional] which url to send the update data. Default is the application main page (index.php/main.php)
     * @param string $method [optional] which method to use to send the update data, default is POST
     * @return
     */
    public static function renderLocationUpdateForm($lon, $lat, $actionurl=HOME_URL, $method='POST') {
        $html = '<div id="modalPage">';
        $html .= '<div class="modalBackground">';
        $html .= '</div>';  // modalBackground
        $html .= '<div id="modalContainer" class="modalContainer">';
        $html .= '<div class="modal">';
        $html .= '<div class="modalBody">';


        $html .= '<form method="' . $method . '" name="submitForm' . '" action="' . $actionurl . '">';
        $html .= "\n" . '<input type="hidden" id="action" name="action" value="locationupdate"/>';
        $html .= "\n" . '<input id="input_lon"  name="lon" type="hidden" value="' . $lon . '"/>';
        $html .= "\n" . '<input id="input_lat" name="lat" type="hidden" value="' . $lat . '"/>';
        $html .= "\n" . '<div id="wrapper">';
        $html .= "\n" . '<div id="headerBar">';
        $html .= "\n" . '<div id="leftHeader">';
        $html .= "\n" . '<img src="' . self::getResource('images/pop_up/message_icon.png') . '" />';
        $html .= "\n" . '</div>';      // leftHeader
        $html .= "\n" . '<div id="rightHeader">';
        $html .= "\n" . '<h1>' . I18n::getMessage('locationupdate.title') . '</h1>';
        $html .= "\n" . '</div>';      // rightHeader
        $html .= "\n" . '</div>';      // headerBar
        $html .= "\n" . '<div id="horizLine">';
        $html .= "\n" . '</div>';      // horizLine
        $html .= "\n" . '<div id="textBlock">';
        $html .= "\n" . '<textarea id="messageBox" name="data">' . I18n::getMessage('locationupdate.defaultmessage') . '</textarea>';
        $html .= "\n" . '</div>';   // textBlock
        $html .= "\n" . '<div id="locBlock">';
        $html .= "\n" . '<img src="' . self::getResource('images/icon/compas_small.png') . '" />';
        $html .= "\n" . '<div id="loctext">';
        $html .= "\n" . '</div>';   // loctext
        $html .= "\n" . '</div>';   // locBlock
        $html .= "\n" . '<div id="confirmArea">';
        $html .= "\n" . '<div id="facebookConf">';
        $html .= "\n" . '<div id="checkFacebook">';
        $html .= "\n" . '<input type="checkbox" id="facebookCheck" name="publish" checked="checked">';
        $html .= "\n" . '</div>';   // checkFacebook
        $html .= "\n" . '<div id="textFacebook">' . I18n::getMessage('locationupdate.fbpublish') . '</div>';
        $html .= "\n" . '</div>';   // facebookConf
        $html .= "\n" . '<div id="buttonConf">';
        $html .= "\n" . '<div id="leftBlock">';
        $html .= "\n" . '</div>';   // leftBlock
        $html .= "\n" . '<div id="rightBlock">';
        $html .= "\n" . '<div id="exitButton">';
        $html .= "\n" . '<img src="' . self::getResource('images/pop_up/cancel_button.png') . '" onclick="hideModal(\'modalPage\');"/>';
        $html .= "\n" . '</div>';   // exitButton
        $html .= "\n" . '<div id="sendButton">';
        $html .= "\n" . '<input type="image" src="' . self::getResource('images/pop_up/send_button.png') . '" />';
        $html .= "\n" . '</div>';   // sendButton
        $html .= "\n" . '</div>';   // rightBlock
        $html .= "\n" . '</div>';   // buttonConf
        $html .= "\n" . '</div>';   // confirmArea
        $html .= "\n" . '</div>';   // wrapper
        $html .= "\n" . '</form>';
        $html .= "\n" . '</div>';   // modalBody
        $html .= "\n" . '</div>';   // modal
        $html .= "\n" . '</div>';   // modalContainer
        $html .= "\n" . '</div>';   // modalPage

        return $html;
    }

    /**
     * Renders the footer section of the page.
     *
     * @return
     */
    public static function render_footer() {
//        $html = '<div class="IDname">';
//        $html .= '<br><a href="http://' . $_SERVER['SERVER_NAME'] . '/invite.php?referer=' . $_SERVER['PHP_SELF'] . '">' . I18n::getMessage('invite.link') . '</a>';
//        $html .= '</div>';
//
//        return $html;
        return '';
    }

    /**
     * Converts unix time (EPOCH) to form '...  ago'
     *
     * @param integer $unix_date UNIX EPOCH time
     * @param boolean $html_format if true, then HTML entities are used (e.g. ' ' => '&nbsp;'). Default is true.
     * @return
     */
    public static function epochToAgo($unix_date, $html_format=TRUE) {
        if (empty($unix_date)) {
            return I18n::getMessage('time.unknown');
        }

        $periods = array("second", "minute", "hour", "day", "week", "month", "year", "decade");
        $lengths = array("60", "60", "24", "7", "4.35", "12", "10");

        $now = time();
        $difference = $now - $unix_date;

        for ($j = 0; $difference >= $lengths[$j] && $j < count($lengths) - 1; $j++) {
            $difference /= $lengths[$j];
        }

        $difference = round($difference);

        return $difference . ($html_format ? '&nbsp;' : ' ') . I18n::getMessage('time.' . $periods[$j], ($difference != 1 ? 1 : 0)) . ($html_format ? '&nbsp;' : ' ') . I18n::getMessage('time.ago');
    }

    /**
     * Calculates the distance between 2 users.
     * The calculation algorithm got from http://snipplr.com/view/2531/calculate-the-distance-between-two-coordinates-latitude-longitude/
     * 
     * @param User $user1
     * @param User $user2
     * @return string representing the distance between the 2 user
     */
    public static function renderDistance($user1, $user2) {
        $km = self::computeDistance($user1, $user2);

        if ($km == -1) {
            return I18n::getMessage('distance.unknown');
        } else if ($km > 10) {
            return sprintf("%d " . I18n::getMessage('distance.km'), $km);
        } else if ($km > 1) {
            return sprintf("%.1f " . I18n::getMessage('distance.km'), $km);
        } else {
            return sprintf("%d " . I18n::getMessage('distance.m'), $km * 1000);
        }
    }

    /**
     * Returns 'img' HTML tag with icon according to the distance.
     * 
     * @param object $user1
     * @param object $user2
     * @return 
     */
    public static function renderDistanceIcon($user1, $user2) {
        $km = self::computeDistance($user1, $user2);

        if ($km == -1) {
            return '';
        } else if ($km < WALK_CAR_BORDER) {
            return '<img src="' . self::getResource('images/icon/info/walk_icon_gray.png') . '"/>';
        } else if ($km < CAR_AEROPLANE_BORDER) {
            return '<img src="' . self::getResource('images/icon/info/car_icon_gray.png') . '"/>';
        } else if ($km < AEROPLANE_ROCKET_BORDER) {
            return '<img src="' . self::getResource('images/icon/info/aeroplane_icon_gray.png') . '"/>';
        } else {
            return '<img src="' . self::getResource('images/icon/info/rocket_icon_gray.png') . '"/>';
        }
    }

    /**
     * Returns just image name with icon according to the distance.
     * 
     * @param object $user1
     * @param object $user2
     * @return 
     */
    public static function renderDistanceIconFileName($user1, $user2) {
        $km = self::computeDistance($user1, $user2);

        if ($km == -1) {
            return '';
        } else if ($km < WALK_CAR_BORDER) {
            return self::getResource('images/icon/info/walk_icon_gray.png');
        } else if ($km < CAR_AEROPLANE_BORDER) {
            return self::getResource('images/icon/info/car_icon_gray.png');
        } else if ($km < AEROPLANE_ROCKET_BORDER) {
            return self::getResource('images/icon/info/aeroplane_icon_gray.png');
        } else {
            return self::getResource('images/icon/info/rocket_icon_gray.png');
        }
    }

    /**
     * Returns just icon name according to the distance.
     * 
     * @param object $user1
     * @param object $user2
     * @return 
     */
    public static function renderDistanceIconName($user1, $user2) {
        $km = self::computeDistance($user1, $user2);

        if ($km == -1) {
            return '';
        } else if ($km < WALK_CAR_BORDER) {
            return 'walk';
        } else if ($km < CAR_AEROPLANE_BORDER) {
            return 'car';
        } else if ($km < AEROPLANE_ROCKET_BORDER) {
            return 'aeroplane';
        } else {
            return 'rocket';
        }
    }

    /**
     * Computes the distance between the 2 users in kilometers;
     * If any of the both users doesn't have set his location, then -1 is returned.
     * 
     * @param User $user1
     * @param User $user2
     * @return -1 if distance is unknown
     */
    public static function computeDistance($user1, $user2) {
        if (!isset($user1) || !isset($user2)
                || !isset($user1->fb_location) || !isset($user2->fb_location)
                || !isset($user1->fb_location->lon) || !isset($user1->fb_location->lat)
                || $user1->fb_location->lon == '' || $user1->fb_location->lat == ''
                || !isset($user2->fb_location->lon) || !isset($user2->fb_location->lat)
                || $user2->fb_location->lon == '' || $user2->fb_location->lat == '') {
            return -1;  // unkown
        }

        $lon1 = $user1->fb_location->lon;
        $lat1 = $user1->fb_location->lat;
        $lon2 = $user2->fb_location->lon;
        $lat2 = $user2->fb_location->lat;

        $pi80 = M_PI / 180;
        $lat1 *= $pi80;
        $lon1 *= $pi80;
        $lat2 *= $pi80;
        $lon2 *= $pi80;
        $r = 6372.797; // mean radius of Earth in km
        $dlat = $lat2 - $lat1;
        $dlon = $lon2 - $lon1;
        $a = sin($dlat / 2) * sin($dlat / 2) + cos($lat1) * cos($lat2) * sin($dlon / 2) * sin($dlon / 2);
        $c = 2 * atan2(sqrt($a), sqrt(1 - $a));
        $km = $r * $c;

        return $km;
    }

    /**
     * Returns an associative array with distance informations: value and units.
     * If any of the users doesn't have specified his location, then both fields are set to null;
     * 
     * @param object $user1
     * @param object $user2
     * @return 
     */
    public static function getDistanceArray($user1, $user2) {
        $returnArray = array();
        $km = self::computeDistance($user1, $user2);

        if ($km == -1) {
            $returnArray['value'] = NULL;
            $returnArray['units'] = NULL;
        } else if ($km > 10) {
            $returnArray['value'] = sprintf("%d", $km);
            $returnArray['units'] = I18n::getMessage('distance.km');
        } else if ($km > 1) {
            $returnArray['value'] = sprintf("%.1f", $km);
            $returnArray['units'] = I18n::getMessage('distance.km');
        } else {
            $returnArray['value'] = sprintf("%d", $km * 1000);
            $returnArray['units'] = I18n::getMessage('distance.m');
        }

        return $returnArray;
    }

}

?>
